<html>
<META http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<head>
<title>Section 6.1.&nbsp; Array Fundamentals</title>
<link rel="STYLESHEET" type="text/css" href="images/style.css">
<link rel="STYLESHEET" type="text/css" href="images/docsafari.css">
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr><td><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-6.html><img src="images/prev.gif" width="60" height="17" border="0" align="absmiddle" alt="Previous Page"></a>
<td align="right"><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-6-SECT-2.html><img src="images/next.gif" width="60" height="17" border="0" align="absmiddle" alt="Next Page"></a>
</div></td></tr></table>
<br><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td valign="top"><a name="learnphpmysql-CHP-6-SECT-1"></a>
<h3 id="631368-926" class="docSection1Title">6.1. Array Fundamentals</h3>
<a name="IDX-CHP-6-0233"></a> 
<a name="IDX-CHP-6-0234"></a> 

<p class="docText">When working with arrays, there are two new terms: elements<a name="IDX-CHP-6-0235"></a> 
 and indexes. <span class="docEmphasis">Elements</span> are the values that are stored in the array. Each element in the array is referenced by an <span class="docEmphasis">index</span> that identifies the element by any other unique element in the array. The index value can be a number or a string, but it must be unique. You can think of an array like a spreadsheet or a database that has only two columns. The first column selects the row in the spreadsheet, while the second column contains a stored value.</p>
<a name="learnphpmysql-CHP-6-SECT-1.1"></a>
<h4 id="title-IDAE11ME" class="docSection2Title">6.1.1. Associative Versus Numeric Indexed Arrays</h4>
<p class="docText"><span class="docEmphasis">Numeric</span> arrays use numbers as their indexes while <span class="docEmphasis">associative</span><a name="IDX-CHP-6-0236"></a> 
 arrays use stings. When using associative arrays,<a name="IDX-CHP-6-0237"></a> 
 you must supply an index string each time you add an element. Numeric arrays allow you to just add the element, and PHP automatically assigns the first free number, starting at 0.</p>
<p><table border="0" bgcolor="black" cellspacing="0" cellpadding="1" width="90%" align="center"><tr><td><table bgcolor="white" width="100%" border="0" cellspacing="0" cellpadding="6"><tr><td width="60" valign="top"><img src="images/warning_yellow.jpg" width="51" height="36" alt=""></td><TD valign="top">
<p class="docText">Be careful, since most people tend to start counting at 1 not 0. If you're not careful, you might end up being off by one when accessing your array. This is called an off-by-one error! The last element in a numeric<a name="IDX-CHP-6-0238"></a> 
 array is accessed as the length of the array minus 1.</p>
</td></TR></table></TD></tr></table></P><br>
<p class="docText">A common symptom of starting to access the values of your array at 1 instead of 0 is attempting to access the last value and finding it's not there! For instance, if you use a numeric array to store four elements and let PHP pick the number index values, the last value is stored under the index value of 4. For example, <a class="docLink" href="#learnphpmysql-CHP-6-TABLE-1">Table 6-1</a> shows a numeric array with five elements. Attempting to access the fifth value at location 5 would miss it, getting the sixth instead. <a class="docLink" href="#learnphpmysql-CHP-6-TABLE-1">Table 6-1</a> displays numeric arrays, starting with the number 0.</p>
<a name="learnphpmysql-CHP-6-TABLE-1"></a><p><table cellspacing="0" FRAME="hsides" RULES="all" cellpadding="4" width="100%"><caption><H5 class="docTableTitle">Table 6-1. A numeric array containing colors, starting at zero</h5></caption><colgroup span="2"><col><col></colgroup><thead><tr><th class="thead" scope="col" align="left"><p class="docText">Key</P></th><th class="thead" scope="col" align="left"><p class="docText">Value</p></th></tr></thead><TR><td class="docTableCell" align="left"><p class="docText">0</p></td><td class="docTableCell" align="left"><p class="docText">Black</P></TD></tr><tr><td class="docTableCell" align="left"><p class="docText">1</p></TD><td class="docTableCell" align="left"><p class="docText">Blue</P></td></TR><TR><TD class="docTableCell" align="left"><p class="docText">2</p></td><td class="docTableCell" align="left"><p class="docText">Red</p></td></tr><tr><td class="docTableCell" align="left"><p class="docText">3</p></td><td class="docTableCell" align="left"><p class="docText">Green</p></td></tr><TR><td class="docTableCell" align="left"><p class="docText">4</p></TD><TD class="docTableCell" align="left"><p class="docText">Purple</p></TD></tr></table></p><br>
<p class="docText">Internally, PHP stores numeric arrays in the same way it stores associative arrays. Numeric arrays are provided because they make it easier to loop through a set of data, since you need only to perform an addition on the key to access the next value.</P>

<a name="learnphpmysql-CHP-6-SECT-1.2"></a>
<h4 id="title-IDAS51ME" class="docSection2Title">6.1.2. Creating an Array</h4>
<a name="IDX-CHP-6-0239"></a> 
<a name="IDX-CHP-6-0240"></a> 
<a name="IDX-CHP-6-0241"></a> 

<p class="docText">To create an array, you must specify the elements and index values. In <a class="docLink" href="#learnphpmysql-CHP-6-TABLE-2">Table 6-2</a>, we show a sample associative array that uses household objects and relates them to strings that describe their shapes.</P>
<a name="learnphpmysql-CHP-6-TABLE-2"></a><p><table cellspacing="0" FRAME="hsides" RULES="all" cellpadding="4" width="100%"><caption><h5 class="docTableTitle">Table 6-2. An associative array that relates objects to their shapes</H5></caption><colgroup span="2"><col><col></colgroup><thead><tr><th class="thead" scope="col" align="left"><p class="docText">Key</p></th><th class="thead" scope="col" align="left"><p class="docText">Value</p></th></tr></thead><TR><TD class="docTableCell" align="left"><p class="docText">Soda Can</p></td><td class="docTableCell" align="left"><p class="docText">Cylinder</p></TD></tr><TR><td class="docTableCell" align="left"><p class="docText">Note Pad</P></TD><TD class="docTableCell" align="left"><p class="docText">Rectangle</p></td></tr><tr><td class="docTableCell" align="left"><p class="docText">Apple</p></td><td class="docTableCell" align="left"><p class="docText">Sphere</p></td></tr><tr><td class="docTableCell" align="left"><p class="docText">Orange</p></TD><td class="docTableCell" align="left"><p class="docText">Sphere</p></TD></TR><tr><TD class="docTableCell" align="left"><p class="docText">Phone book</p></td><td class="docTableCell" align="left"><p class="docText">Rectangle</P></td></tr></table></P><br>
<p class="docText">The elements of an array can be anything, including strings, numbers, and even other arrays! The key field must be a <span class="docEmphasis">scalar</span>. Scalar values are simple values such as a number or text, including <tt>true</tt> or <tt>false</tt>, not data that can have more than one value such as an array. The key field of an array must also be unique. Should you attempt to assign a value using a key you specified already, the new value simply replaces the old value.</P>
<p class="docText">Short yet meaningful values for your index keys make your programs run faster, which will make them easier to maintain.</p>
<a name="learnphpmysql-CHP-6-SECT-1.2.1"></a>
<h5 id="title-IDAZD2ME" class="docSection3Title">6.1.2.1. Assignment via array identifiers</h5>
<a name="IDX-CHP-6-0242"></a> 

<p class="docText">Now that you know what can go into an array, you'll need a way to get values into the array. PHP provides two ways of assigning values to arrays. We'll discuss <span class="docEmphasis">array identifiers</span> for assignment first.</p>
<p class="docText">Array identifiers look like normal variable assignments except a pair of brackets (<tt>[]</tt>) are added after the name of the array variable. You can optionally add an index value between the brackets. If you don't supply an index, PHP automatically picks the lowest empty numeric index value for the array. For example, to assign the first two days of the week to a numeric indexed array, you would use:</P>
<pre>
&lt;?php
$weekdays[]='Monday';
$weekdays[]='Tuesday';
?&gt;
</pre><BR>

<p class="docText">You could also specify the index values, which has the same end result as:</p>
<pre>
&lt;?php
$weekdays[0]='Monday';
$weekdays[1]='Tuesday';
?&gt;
</pre><br>

<p class="docText">If you do specify the index yourself, be careful not to skip over numbers:</p>
<pre>
&lt;?php
$weekdays[0]='Monday';
$weekdays[1]='Tuesday';
$weekdays[3]='Wednesday';
?&gt;
</pre><br>

<p class="docText">This code creates an array that doesn't have a value assigned for the index of 2. That might be OK, but if you're going through the array values sequentially and your code unexpectedly encounters a missing value, that'll cause problems, but not a PHP error.</P>

<a name="learnphpmysql-CHP-6-SECT-1.2.2"></a>
<h5 id="title-IDA0E2ME" class="docSection3Title">6.1.2.2. Assignment using array</H5>
<a name="IDX-CHP-6-0243"></a> 
<a name="IDX-CHP-6-0244"></a> 

<p class="docText">The other way to assign values to an array is to use the <tt>array</tt> function. The <tt>array</tt> function allows you to create your array and assign multiple elements all at once. The array takes pairs of index keys and values as parameters. It returns an array assigned to a variable. The elements to be assigned are separated by commas.</p>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-6-EX-1">Example 6-1</a> creates a numeric array using <tt>array</tt>.</P>
<a name="learnphpmysql-CHP-6-EX-1"></a><H5 id="title-IDAZF2ME" class="docExampleTitle">Example 6-1. Using the array function to create an array of weekdays</H5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><td>

<pre>
&lt;?php
$weekdays=array('Monday',
                'Tuesday',
                'Wednesday',
                'Thursday',
                'Friday',
                'Saturday',
                'Sunday');
?&gt;
</pre><br>

</td></tr></table></p>
<p class="docText">The whitespace you see in this code makes adding elements to the array easier. You can create as many elements in the array as you wish.</p>
<p class="docText">In <a class="docLink" href="#learnphpmysql-CHP-6-EX-2">Example 6-2</a>, we create an associative array using the format <tt><i>index</i></tt> <tt>=&gt;</tt> <tt><i>value</i></tt>.</p>
<a name="learnphpmysql-CHP-6-EX-2"></a><h5 id="title-IDASG2ME" class="docExampleTitle">Example 6-2. Creating an associative array of shapes</H5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><TD>

<pre>
&lt;?php
  $shapes=array('Soda Can' =&gt; 'Cylinder',
                'Note Pad' =&gt; 'Rectangle',
                'Apple' =&gt; 'Sphere',
                'Orange' =&gt; 'Sphere',
                'Phonebook' =&gt; 'Rectangle');
?&gt;
</pre><BR>

</td></TR></table></p>
<p><table border="0" bgcolor="black" cellspacing="0" cellpadding="1" width="90%" align="center"><tr><TD><table bgcolor="white" width="100%" border="0" cellspacing="0" cellpadding="6"><tr><td width="60" valign="top"><img src="images/warning_yellow.jpg" width="51" height="36" alt=""></TD><td valign="top">
<p class="docText">When assigning array names, you need to be careful not to use the same name as another variable, since they share the same set of names. Assigning a variable to the same name as an existing array will overwrite the array without warning.</p>
</TD></tr></table></td></tr></table></p><BR>
<p class="docText">If you're not sure whether a variable is an array, you can use <tt>is_array</tt>. For example, you'd enter the code:</P>
<pre>
&lt;?php
$yes = array('this', 'is', 'an array');
echo is_array($yes) ? 'Array' : 'not an Array';
echo "&lt;br&gt;";
$no = 'this is a string';
echo is_array($no) ? 'Array' : 'Not an Array';
?&gt;
</pre><br>

<p class="docText">This outputs:</p>
<pre>
Array
Not an Array
</pre><br>

<p class="docText">Since you know how to assign values to an array and how to find out whether a variable is an array, it's time to discuss retrieving those values.</p>

<a name="learnphpmysql-CHP-6-SECT-1.2.3"></a>
<H5 id="title-IDAQH2ME" class="docSection3Title">6.1.2.3. Looping through and referencing array values</h5>
<a name="IDX-CHP-6-0245"></a> 
<a name="IDX-CHP-6-0246"></a> 
<a name="IDX-CHP-6-0247"></a> 
<a name="IDX-CHP-6-0248"></a> 
<a name="IDX-CHP-6-0249"></a> 
<a name="IDX-CHP-6-0250"></a> 

<p class="docText">Items in an array may be individually accessed by including the key to the array in brackets after the name of the variable in the form <tt>$</tt><tt><I>array</i></tt><tt>[</tt><tt><I>index</I></tt><tt>]</tt>. Arrays referenced in a string that have a key value with whitespaces or punctuation must be enclosed in curly braces (<tt>{}</tt>). For example, <a class="docLink" href="#learnphpmysql-CHP-6-EX-3">Example 6-3</a> displays the value of the <tt>$shapes</tt> array for <tt>'Note Pad'</tt>.</P>
<a name="learnphpmysql-CHP-6-EX-3"></a><h5 id="title-IDAPJ2ME" class="docExampleTitle">Example 6-3. Displaying one value from an array</h5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><td>

<pre>
&lt;?php
  $shapes=array('Soda Can' =&gt; 'Cylinder',
                'Note Pad' =&gt; 'Rectangle',
                'Apple' =&gt; 'Sphere',
                'Orange' =&gt; 'Sphere',
                'Phonebook' =&gt; 'Rectangle');
  print "A note pad is a {$shapes['Note Pad']}.";
?&gt;
</pre><br>

</td></tr></table></p>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-6-EX-3">Example 6-3</a> produces:</p>
<pre>
The Note Pad is a Rectangle.
</pre><br>

<p class="docText">In <a class="docLink" href="#learnphpmysql-CHP-6-EX-4">Example 6-4</a>, a <tt>foreach</tt> loop displays all the values in an array. The <tt>foreach</tt> statement is handy, because it automatically advances and reads each value from an array until it reaches the last value <span class="docEmphasis">n</span> in the array. This eliminates having to remember 0-based arrays, and won't run beyond the length of an array, making it a very useful looping construct that avoids common logical errors. <a class="docLink" href="#learnphpmysql-CHP-6-EX-4">Example 6-4</a> shows an array's content using a loop.</p>
<a name="learnphpmysql-CHP-6-EX-4"></a><h5 id="title-IDAUK2ME" class="docExampleTitle">Example 6-4. Display the contents of an array using a loop</h5><P><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><td>

<pre>
&lt;?php
$shapes=array('Soda Can' =&gt; 'Cylinder',
              'Note Pad' =&gt; 'Rectangle',
              'Apple' =&gt; 'Sphere',
              'Orange' =&gt; 'Sphere',
              'Phonebook' =&gt; 'Rectangle');
foreach ($shapes as $key =&gt; $value) {
    print"The $key is a $value.&lt;br&gt;\n";
}
?&gt;
</pre><BR>

</TD></tr></table></P>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-6-EX-4">Example 6-4</a> produces:</p>
<pre>
The Soda Can is a Cylinder.&lt;br&gt;
The Note Pad is a Rectangle.&lt;br&gt;
The Apple is a Sphere.&lt;br&gt;
The Orange is a Sphere.&lt;br&gt;
The Phonebook is a Rectangle.&lt;br&gt;
</pre><br>

<p class="docText">The breaks, <tt>&lt;br&gt;</tt>, won't show up in your browser as they are HTML markup, adding<a name="IDX-CHP-6-0251"></a> 
<a name="IDX-CHP-6-0252"></a> 
 line breaks after each sentence. Each string in the array was processed, so the loop stopped automatically.</p>

<a name="learnphpmysql-CHP-6-SECT-1.2.4"></a>
<H5 id="title-IDAYL2ME" class="docSection3Title">6.1.2.4. Adding values to an array</h5>
<p class="docText">To add values to the end of an existing array, you can use the array identifier. For example, to add <tt>Thursday</tt> to the <tt>$weekdays</tt> array:</p>
<pre>
&lt;?php
$weekdays[] = "Thursday";
?&gt;
</pre><BR>

<p class="docText">To add another shape to your associative array, use a similar syntax:</p>
<pre>
&lt;?php
$shapes["Megaphone"]= "Cone";
?&gt;
</pre><br>

<p class="docText">This works even though the array was created using the <tt>array</tt> function. This leads us to the opposite problem.</P>

<a name="learnphpmysql-CHP-6-SECT-1.2.5"></a>
<h5 id="title-IDARM2ME" class="docSection3Title">6.1.2.5. Counting how many elements are in an array</h5>
<a name="IDX-CHP-6-0253"></a> 
<a name="IDX-CHP-6-0254"></a> 
<a name="IDX-CHP-6-0255"></a> 

<p class="docText">You can use the <tt>count</tt> function to find out how many elements are currently assigned to an array. The <tt>count</tt> function is identical to <tt>sizeof</tt> and can be used interchangeably. <a class="docLink" href="#learnphpmysql-CHP-6-EX-5">Example 6-5</a> counts the elements in the <tt>$shapes</tt> array.</p>
<a name="learnphpmysql-CHP-6-EX-5"></a><h5 id="title-IDAWN2ME" class="docExampleTitle">Example 6-5. Counting the elements in an array</H5><P><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><td>

<pre>
&lt;?php
$shapes=array('Soda Can' =&gt; 'Cylinder',
              'Note Pad' =&gt; 'Rectangle',
              'Apple' =&gt; 'Sphere',
              'Orange' =&gt; 'Sphere',
              'Phonebook' =&gt; 'Rectangle');
$numElements = count($shapes);
print"The array has $numElements elements.&lt;br&gt;\n";
?&gt;
</pre><br>

</td></TR></table></p>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-6-EX-5">Example 6-5</a> displays:</P>
<pre>
The array has 5 elements.
</pre><br>

<p class="docText">The <tt>print</tt> command in <a class="docLink" href="#learnphpmysql-CHP-6-EX-5">Example 6-5</a> is identical to <tt>echo</tt>, for the purposes of arrays. It doesn't matter whether your array is associative or numeric when <tt>count</tt> sizes up your array. If you want the array to sort your data in alphabetical order, you'd use <tt>sort</tt>.</P>

<a name="learnphpmysql-CHP-6-SECT-1.2.6"></a>
<H5 id="title-IDAZO2ME" class="docSection3Title">6.1.2.6. Sorting arrays</H5>
<p class="docText">This function sorts an array. Elements are arranged from lowest to highest after this function is completed. Numbers are sorted numerically, while strings are sorted alphabetically. This function assigns new keys for the elements in an array. It removes any existing keys you may have assigned, rather than just reordering the keys.</p>
<p><table border="0" bgcolor="black" cellspacing="0" cellpadding="1" width="90%" align="center"><tr><td><table bgcolor="white" width="100%" border="0" cellspacing="0" cellpadding="6"><tr><td width="60" valign="top"><img src="images/tip_yellow.jpg" width="50" height="54" alt=""></td><td valign="top">
<p class="docText">You need to be cautious when sorting<a name="IDX-CHP-6-0256"></a> 
 arrays with mixed type values, because <tt>sort</tt> can produce unpredictable results.</p>
</td></tr></table></td></tr></table></p><BR>
<p class="docText">Using the <tt>shapes</tt> example from <a class="docLink" href="#learnphpmysql-CHP-6-EX-5">Example 6-5</a>, you can sort alphabetically. The code would look like <a class="docLink" href="#learnphpmysql-CHP-6-EX-6">Example 6-6</a>.</p>
<a name="learnphpmysql-CHP-6-EX-6"></a><h5 id="title-IDACQ2ME" class="docExampleTitle">Example 6-6. Using sort to alphabetize</H5><P><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><TD>

<pre>
&lt;?php
$shapes = array("rectangle", "cylinder", "sphere");
sort($shapes);
//The foreach loop selects each element from the array and assigns its value to $key
//before executing the code in the block.
foreach ($shapes as $key =&gt; $val) {
 echo "shapes[" . $key . "] = " . $val . "&lt;br&gt;";
}
?&gt;
</pre><br>

</td></tr></table></P>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-6-EX-6">Example 6-6</a> outputs to:</p>
<pre>
shapes[0] = cylinder
shapes[1] = rectangle
shapes[2] = sphere
</pre><br>

<p class="docText">As you can see, the shapes have been sorted alphabetically. <a class="docLink" href="#learnphpmysql-CHP-6-TABLE-3">Table 6-3</a> shows an optional second parameter <tt>sort_flags</tt> that can be used to modify the sorting behavior using these values.</P>
<a name="learnphpmysql-CHP-6-TABLE-3"></a><p><table cellspacing="0" FRAME="hsides" RULES="all" cellpadding="4" width="100%"><caption><h5 class="docTableTitle">Table 6-3. sort_flags</H5></caption><colgroup span="2"><col><col></colgroup><thead><tr><th class="thead" scope="col" align="left"><p class="docText">sort_flag</p></th><th class="thead" scope="col" align="left"><p class="docText">Definition</p></th></tr></thead><TR><TD class="docTableCell" align="left"><p class="docText">sort_regular</p></td><td class="docTableCell" align="left"><p class="docText">Compares items normally, but doesn't change types</p></TD></tr><TR><td class="docTableCell" align="left"><p class="docText">sort_numeric</P></TD><TD class="docTableCell" align="left"><p class="docText">Compares items numerically</p></td></tr><tr><td class="docTableCell" align="left"><p class="docText">sort_string</p></td><td class="docTableCell" align="left"><p class="docText">Compares items as strings</p></td></tr><tr><td class="docTableCell" align="left"><p class="docText">sort_locale_string</p></TD><td class="docTableCell" align="left"><p class="docText">Compares items as strings, based on the current locale</p></TD></TR></table></p><BR>
<p class="docText">You've learned a lot about arrays; now let's move on to multidimensional<a name="IDX-CHP-6-0257"></a> 
 arrays that hold more elements instead of just simple values.</p>


<a name="learnphpmysql-CHP-6-SECT-1.3"></a>
<h4 id="title-IDA0T2ME" class="docSection2Title">6.1.3. Multidimensional Arrays</h4>
<a name="IDX-CHP-6-0258"></a> 

<p class="docText">While we've only shown arrays that hold simple values like strings so far, remember that an array can also store another array as an element. Multidimensional arrays exploit the fact that an array can have another array as an element. Each set of keys and values represents a <span class="docEmphasis">dimension</span>. Multidimensional arrays have a key and value set for each dimension. Don't worry if that sounds complicated; again, it's really just an array inside of an array, like those Russian dolls that open up to contain yet another smaller doll!</P>
<p class="docText">Expanding upon your <tt>shapes</tt> array, we create a new associative array called <tt>$objects</tt> with keys that are the names of the objects. Each element of the <tt>$objects</tt> array is another associative array containing the keys <tt>shape, color</tt>, and <tt>material</tt> with the associated values as the elements. <a class="docLink" href="#learnphpmysql-CHP-6-TABLE-4">Table 6-4</a> shows you what data is being stored.</p>
<a name="learnphpmysql-CHP-6-TABLE-4"></a><p><table cellspacing="0" FRAME="hsides" RULES="all" cellpadding="4" width="100%"><caption><H5 class="docTableTitle">Table 6-4. A multidimensional array that now stores shape, color, and material for each object</h5></caption><colgroup span="3"><col><col><col></colgroup><thead><tr><th class="thead" scope="col" align="left"><p class="docText">First key</P></th><th class="thead" scope="col" align="left"><p class="docText">Second key</p></th><th class="thead" scope="col" align="left"><p class="docText">Value</p></th></tr></thead><tr><TD class="docTableCell" align="left"><p class="docText">Soda can</P></td><td class="docTableCell" align="left"><p class="docText">Shape</p></td><TD class="docTableCell" align="left"><p class="docText">Cylinder</p></TD></tr><TR><TD class="docTableCell">&nbsp;</TD><td class="docTableCell" align="left"><p class="docText">Color</p></td><td class="docTableCell" align="left"><p class="docText">Red</p></td></tr><tr><td class="docTableCell">&nbsp;</td><td class="docTableCell" align="left"><p class="docText">Material</p></td><td class="docTableCell" align="left"><p class="docText">Metal</P></td></tr><TR><TD class="docTableCell" align="left"><p class="docText">Note Pad</p></TD><td class="docTableCell" align="left"><p class="docText">Shape</p></td><TD class="docTableCell" align="left"><p class="docText">Rectangle</p></td></TR><tr><td class="docTableCell">&nbsp;</TD><td class="docTableCell" align="left"><p class="docText">Color</p></td><td class="docTableCell" align="left"><p class="docText">White</P></TD></tr><tr><td class="docTableCell">&nbsp;</td><TD class="docTableCell" align="left"><p class="docText">Material</p></TD><td class="docTableCell" align="left"><p class="docText">Paper</P></TD></TR><tr><td class="docTableCell" align="left"><p class="docText">Apple</p></td><td class="docTableCell" align="left"><p class="docText">Shape</p></td><td class="docTableCell" align="left"><p class="docText">Sphere</p></td></tr><tr><td class="docTableCell">&nbsp;</td><TD class="docTableCell" align="left"><p class="docText">Color</p></td><TD class="docTableCell" align="left"><p class="docText">Red</P></td></TR><tr><td class="docTableCell">&nbsp;</td><TD class="docTableCell" align="left"><p class="docText">Material</p></td><TD class="docTableCell" align="left"><p class="docText">Fruit</p></td></TR><tr><td class="docTableCell" align="left"><p class="docText">Orange</p></td><TD class="docTableCell" align="left"><p class="docText">Shape</P></td><td class="docTableCell" align="left"><p class="docText">Sphere</p></td></TR><tr><TD class="docTableCell">&nbsp;</td><TD class="docTableCell" align="left"><p class="docText">Color</P></TD><td class="docTableCell" align="left"><p class="docText">Orange</p></td></tr><tr><td class="docTableCell">&nbsp;</td><td class="docTableCell" align="left"><p class="docText">Material</p></td><td class="docTableCell" align="left"><p class="docText">Fruit</p></td></tr><TR><td class="docTableCell" align="left"><p class="docText">Phonebook</p></TD><TD class="docTableCell" align="left"><p class="docText">Shape</p></TD><td class="docTableCell" align="left"><p class="docText">Rectangle</p></td></TR><tr><td class="docTableCell">&nbsp;</TD><td class="docTableCell" align="left"><p class="docText">Color</p></TD><td class="docTableCell" align="left"><p class="docText">Yellow</p></td></tr><TR><TD class="docTableCell">&nbsp;</td><td class="docTableCell" align="left"><p class="docText">Material</p></td><TD class="docTableCell" align="left"><p class="docText">Paper</p></TD></tr></table></P><BR>
<p class="docText">To create the array in <a class="docLink" href="#learnphpmysql-CHP-6-TABLE-4">Table 6-4</a>, use the array function like that in <a class="docLink" href="#learnphpmysql-CHP-6-EX-7">Example 6-7</a>.</P>
<a name="learnphpmysql-CHP-6-EX-7"></a><h5 id="title-IDAG32ME" class="docExampleTitle">Example 6-7. Creating a multidimensional array</h5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><td>

<pre>
&lt;?php
$objects=array('Soda Can' =&gt;    array('Shape'    =&gt; 'Cylinder',
                                      'Color'    =&gt; 'Red',
                                      'Material' =&gt; 'Metal'),
               'Note Pad' =&gt;    array('Shape'    =&gt; 'Rectangle',
                                      'Color'    =&gt; 'White',
                                      'Material' =&gt; 'Paper'),
               'Apple' =&gt;       array('Shape'    =&gt; 'Sphere',
                                      'Color'    =&gt; 'Red',
                                      'Material' =&gt; 'Fruit'),
               'Orange' =&gt;      array('Shape'    =&gt; 'Sphere',
                                      'Color'    =&gt; 'Orange',
                                      'Material' =&gt; 'Fruit'),
               'Phonebook' =&gt;  array('Shape'    =&gt; 'Rectangle',
                                      'Color'    =&gt; 'Yellow',
                                      'Material' =&gt; 'Paper'));
echo $objects['Soda Can']['Shape'];
?&gt;
</pre><br>

</td></tr></table></p>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-6-EX-7">Example 6-7</a> displays:</p>
<pre>
Cylinder
</pre><br>

<p class="docText">We're able to access the second dimension of the array by using a second set of brackets (<tt>[]</tt>) to specify the second key. If the array has more dimensions than just two, you must specify the key for each dimension. True to form, if you access <tt>$objects['Orange']</tt>, you would get an array.</p>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-6-EX-8">Example 6-8</a> displays all of the elements of both arrays.</p>
<a name="learnphpmysql-CHP-6-EX-8"></a><h5 id="title-IDAG42ME" class="docExampleTitle">Example 6-8. Displaying a multidimensional array</H5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><TD>

<pre>
&lt;?php
foreach ($objects as $obj_key =&gt; $obj)
{
  echo "$obj_key:&lt;br&gt;";
  while (list ($key,$value)=each ($obj))
  {
     echo "$key = $value ";
  }
 echo "&lt;br&gt;";
}
?&gt;
</pre><BR>

</td></TR></table></p>
<p class="docText">The code displays something like <a class="docLink" href="#learnphpmysql-CHP-6-FIG-1">Figure 6-1</a>.</p>
<a name="learnphpmysql-CHP-6-FIG-1"></a><p><center>
<H5 class="docFigureTitle">Figure 6-1. The multidimensional array displays in the browser</h5>
<img border="0" alt="" id="195131084199" width="549" height="231" SRC="images/learnphpmysql_0601.jpg">
</center></p><BR>
<p class="docText">However, there's more than one way to display an array.</p>
<p class="docText">There's also a built-in function to display an array all in one step, called <tt>var_dump</tt>. If you specify your array from <a class="docLink" href="#learnphpmysql-CHP-6-EX-7">Example 6-7</a> like this:</p>
<pre>
echo var_dump($ojbects);
</pre><BR>

<p class="docText">you see:</p>
<pre>
array(5) { ["Soda Can"]=&gt; array(3) { ["Shape"]=&gt; string(8)
"Cylinder" ["Color"]=&gt; string(3) "Red" ["Material"]=&gt; string(5) "Metal" }
["Note Pad"]=&gt; array(3) { ["Shape"]=&gt; string(9) "Rectangle" ["Color"]=&gt; string(5)
"White" ["Material"]=&gt; string(5) "Paper" } ["Apple"]=&gt; array(3) { ["Shape"]=&gt;
string(6) "Sphere" ["Color"]=&gt; string(3) "Red" ["Material"]=&gt; string(5) "Fruit" }
["Orange"]=&gt; array(3) { ["Shape"]=&gt; string(6) "Sphere" ["Color"]=&gt; string(6)
"Orange" ["Material"]=&gt; string(5) "Fruit" } ["Phonebook"]=&gt; array(3) {
["Shape"]=&gt; string(9) "Rectangle" ["Color"]=&gt; string(6) "Yellow"
["Material"]=&gt; string(5) "Paper" } }
</pre><br>

<p class="docText">While it's not formatted as nicely as <a class="docLink" href="#learnphpmysql-CHP-6-EX-8">Example 6-8</a>, it's less work and can take an array as its input. This is a great tool for debugging the values in an array. The numbers after the data types indicate how long each one is; for instance in this example, there are five elements in the first level of the array and each string has a different length based on its contents. There are general tools available for debugging your PHP code, and there are also PHP tools that can help you debug your code yourself, without the purchase of a separate program. Xdebug is a free debugger available from <a class="docLink" target="_blank" href="http://xdebug.org/">http://xdebug.org/</a>. Zend Studio, available from <a class="docLink" target="_blank" href="http://www.zend.com/store/products/zend-studio/">http://www.zend.com/store/products/zend-studio/</a>, includes a debugger as part of its Integrated Development Environment (IDE). An IDE includes editing, testing, and debugging in one application.</p>

<a name="learnphpmysql-CHP-6-SECT-1.4"></a>
<h4 id="title-IDAJA3ME" class="docSection2Title">6.1.4. Extracting Variables from an Array</H4>
<a name="IDX-CHP-6-0259"></a> 
<a name="IDX-CHP-6-0260"></a> 
<a name="IDX-CHP-6-0261"></a> 
<a name="IDX-CHP-6-0262"></a> 

<p class="docText">PHP provides a shortcut for placing elements in an array into variables, where the variables have the same names as the keys. This works for associative arrays only, unless of course, you specify a prefix that we'll talk about next. The <tt>exTRact</tt><a name="IDX-CHP-6-0263"></a> 
 function takes an array as a parameter and creates the local variables, as shown in <a class="docLink" href="#learnphpmysql-CHP-6-EX-9">Example 6-9</a>.</p>
<a name="learnphpmysql-CHP-6-EX-9"></a><h5 id="title-IDAPB3ME" class="docExampleTitle">Example 6-9. Using extract on an associative array</h5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><TR><td>

<pre>
&lt;?php
$shapes=array('SodaCan' =&gt; 'Cylinder',
              'NotePad' =&gt; 'Rectangle',
              'Apple' =&gt; 'Sphere',
              'Orange' =&gt; 'Sphere',
              'PhoneBook' =&gt; 'Rectangle');

extract($shapes);
// $SodaCan, $NotePad, $Apple, $Orange, and $PhoneBook are now set
echo $Apple;
echo "&lt;br&gt;";
echo $NotePad;
?&gt;
</pre><BR>

</td></TR></table></P>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-6-EX-9">Example 6-9</a> produces browser output like that in <a class="docLink" href="#learnphpmysql-CHP-6-FIG-2">Figure 6-2</a>.</P>
<a name="learnphpmysql-CHP-6-FIG-2"></a><p><center>
<h5 class="docFigureTitle">Figure 6-2. The values from the array now appear in their own variables</h5>
<img border="0" alt="" id="195131084199" width="456" height="150" SRC="images/learnphpmysql_0602.jpg">
</center></p><br>
<p class="docText">Notice that the spaces were removed from the key values in the <tt>$shapes</tt> array. Although they wouldn't have caused an error, they also wouldn't be accessible as variables, since variable names cannot have spaces. You need to use underscores instead of spaces in variable names. Also, if a variable already exists with the same name as a key in the array to expand, its value is overwritten by the value from the expanded array.</p>
<p class="docText">One way to prevent possibly overwriting a variable you're already using is to include a second set of parameters to <tt>expand</tt> that specify a prefix to be prepended to the name of each variable you extract from the array. It's specified using this syntax:</p>
<pre>
expand($<tt><i>array</i></tt>,EXtr_PREFIX_ALL,"<tt><i>the prefix</i></tt>");
</pre><br>

<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-6-EX-10">Example 6-10</a> demonstrates the use of the <tt>EXtr_PREFIX_ALL</tt> option for <tt>exTRact</tt>.</p>
<a name="learnphpmysql-CHP-6-EX-10"></a><h5 id="title-IDAMD3ME" class="docExampleTitle">Example 6-10. Using extract with the EXTR_PREFIX_ALL directive</H5><P><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><TD>

<pre>
&lt;?php
$Apple="Computer";
$shapes=array('SodaCan' =&gt; 'Cylinder',
              'NotePad' =&gt; 'Rectangle',
              'Apple' =&gt; 'Sphere',
              'Orange' =&gt; 'Sphere',
              'PhoneBook' =&gt; 'Rectangle');

extract($shapes,EXTR_PREFIX_ALL,"shapes");
// $shapes_SodaCan, $shapes_NotePad, $shapes_Apple, $shapes_Orange, and
//$shapes_PhoneBook are now set

echo "Apple is $Apple.&lt;br&gt;";
echo "Shapes_Apple is $shapes_Apple";
echo "&lt;br&gt;";
echo "Shapes_NotePad is $shapes_NotePad";
?&gt;
</pre><br>

</td></tr></table></P>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-6-EX-10">Example 6-10</a> returns:</p>
<pre>
Apple is Computer.
Shapes_Apple is Sphere
Shapes_NotePad is Rectangle
</pre><br>

<p class="docText">The <tt>EXTR_PREFIX_ALL</tt> keyword allows you to use <tt>extract</tt> on a numeric array. <a class="docLink" href="#learnphpmysql-CHP-6-EX-11">Example 6-11</a> creates a numeric array, calls <tt>extract</tt> on it, and then accesses the variable for the zero position element.</P>
<a name="learnphpmysql-CHP-6-EX-11"></a><h5 id="title-IDAME3ME" class="docExampleTitle">Example 6-11. Using EXTR_PREFIX_ALL on a numeric array</h5><p><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><TD>

<pre>
&lt;?php
$shapes=array( 'Cylinder',
               'Rectangle');
extract($shapes,EXTR_PREFIX_ALL,"shapes");
echo "Shapes_0 is <B>$shapes_0</b> &lt;br&gt;";
echo "Shapes_1 is <b>$shapes_1</b>";
?&gt;
</pre><br>

</td></tr></table></P>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-6-EX-11">Example 6-11</a> displays:</p>
<pre>
Shapes_0 is Cylinder
Shapes_1 is Rectangle
</pre><BR>

<p class="docText">PHP also gives you a function, called <tt>compact</tt>,<a name="IDX-CHP-6-0264"></a> 
 that does the opposite of <tt>extract</tt>.</P>
<a name="learnphpmysql-CHP-6-SECT-1.4.1"></a>
<H5 id="title-IDAPF3ME" class="docSection3Title">6.1.4.1. Using compact to build an array from variables</H5>
<a name="IDX-CHP-6-0265"></a> 

<p class="docText">The <tt>compact</tt> function is the complement of <tt>extract</tt>. It takes the variables as parameters individually, as arrays, or a combination of both. The <tt>compact</tt> function creates an associative array whose keys are the variable names and whose values are the variable's values. Any names in the array that don't correspond to actual variables are skipped. Arrays of variables as parameters are automatically expanded. Here's an example of <tt>compact</tt> in action:</p>
<pre>
&lt;?php
$SodaCan='Cylinder';
$NotePad='Rectangle';
$Apple = 'Sphere';
$Orange = 'Sphere';
$PhoneBook = 'Rectangle';

$shapes=compact('SodaCan', 'Note Pad', 'Apple', 'Orange', 'PhoneBook');
echo var_dump($shapes);
?&gt;
</pre><br>

<p class="docText">This produces something like <a class="docLink" href="#learnphpmysql-CHP-6-FIG-3">Figure 6-3</a> in your browser.</p>
<a name="learnphpmysql-CHP-6-FIG-3"></a><p><center>
<h5 class="docFigureTitle">Figure 6-3. The browser displaying the variable dump for a compact created array</h5>
<img border="0" alt="" id="195131084199" width="251" height="261" SRC="images/learnphpmysql_0603.jpg">
</center></p><br>


<a name="learnphpmysql-CHP-6-SECT-1.5"></a>
<h4 id="title-IDA2G3ME" class="docSection2Title">6.1.5. Array Functions in PHP</h4>
<p class="docText">Although we've already discussed several array functions<a name="IDX-CHP-6-0266"></a> 
<a name="IDX-CHP-6-0267"></a> 
 such as <tt>count</tt>, there are many more. Following are some of the most common ones that we haven't discussed yet; for a full listing, search <a class="docLink" target="_blank" href="http://www.php.net">http://www.php.net</a>.</p>
<dl class="docList">
<dt><br><p><span class="docPubcolor"><span class="docPubcolor"><span class="docMonofont">Reset(</span></span> <tt><I>array</i></tt><span class="docPubcolor"><span class="docMonofont">)</span></span> </span></p></dt>
<dd><p class="docList">Takes an array as its argument and resets the pointer to the beginning of the array. The <span class="docEmphasis">pointer</span> is how PHP keeps track of the current element in an array when working with functions that can move around in arrays.</P></dd>

<dt><BR><p><span class="docPubcolor"><span class="docPubcolor"><span class="docMonofont">Array_push(</span></span> <tt><I>array,elements</i></tt><span class="docPubcolor"><span class="docMonofont">)</span></span> </span></p></dt>
<dd><p class="docList">Adds one or more elements to the end of an existing array. For example, <tt>array_push($shapes,"rock","paper","scisors");</tt> adds those three elements to an array called <tt>$shapes</tt>.</p></dd>

<dt><BR><p><span class="docPubcolor"><span class="docPubcolor"><span class="docMonofont">Array_pop(</span></span> <tt><i>array</I></tt><span class="docPubcolor"><span class="docMonofont">)</span></span> </span></p></dt>
<dd><p class="docList">Returns and removes the last element of an array. For example, <tt>$last_element=array_pop($shapes);</tt> removes the last element from <tt>$shapes</tt> and assigns it to <tt>$last_element</tt>.</p></dd>

<dt><BR><p><span class="docPubcolor"><span class="docPubcolor"><span class="docMonofont">Array_unshift(</span></span> <tt><i>array,elements</i></tt><span class="docPubcolor"><span class="docMonofont">)</span></span> </span></p></dt>
<dd><p class="docList">Adds one or more elements to the beginning of an existing array. For example, <tt>array_unshift($shapes,"rock","paper","scisors");</tt> adds three elements to the beginning of an array called <tt>$shapes</tt>.</P></dd>

<dt><BR><p><span class="docPubcolor"><span class="docPubcolor"><span class="docMonofont">Array_shift(</span></span> <tt><i>array</i></tt><span class="docPubcolor"><span class="docMonofont">)</span></span> </span></p></dt>
<dd><p class="docList">Returns and removes the first element of an array. For example, <tt>$first_element=array_unshift($shapes);</tt> removes the first element from <tt>$shapes</tt> and assigns it to <tt>$first_element</tt>.</P></dd>

<dt><br><P><span class="docPubcolor"><span class="docPubcolor"><span class="docMonofont">Array_merge(</span></span> <tt><i>array,array</I></tt><span class="docPubcolor"><span class="docMonofont">)</span></span> </span></P></dt>
<dd><p class="docList">Combines two arrays together and returns the new array. For example, <tt>$combined_array=array_merge($shapes,$sizes);</tt> combines the elements of both arrays and assigns the new array to <tt>$combined_array</tt>.</P></dd>

<dt><br><p><span class="docPubcolor"><span class="docPubcolor"><span class="docMonofont">Array_keys(</span></span> <tt><i>array</i></tt><span class="docPubcolor"><span class="docMonofont">)</span></span> </span></p></dt>
<dd><p class="docList">Returns an array containing all of the keys from the supplied array. For example, <tt>$keys=array_keys($shapes);</tt> assigns an array to <tt>$keys</tt> that consists of only the keys like <tt>"Apple"</tt> and <tt>"Note Pad"</tt> from the array in <a class="docLink" href="#learnphpmysql-CHP-6-EX-2">Example 6-2</a>.</p></dd>

<dt><br><p><span class="docPubcolor"><span class="docPubcolor"><span class="docMonofont">Array_values(</span></span> <tt><i>array</i></tt><span class="docPubcolor"><span class="docMonofont">)</span></span> </span></p></dt>
<dd><p class="docList">Returns an array containing all of the values from the supplied array. For example, <tt>$values=array_values($shapes);</tt> assigns an array to <tt>$values</tt> that consists of only the element values like <tt>"Sphere"</tt> and <tt>"Rectangle"</tt> from the array in <a class="docLink" href="#learnphpmysql-CHP-6-EX-2">Example 6-2</a>.</p></dd>

<dt><br><p><span class="docPubcolor"><span class="docPubcolor"><span class="docMonofont">Shuffle(</span></span> <tt><I>array</i></tt><span class="docPubcolor"><span class="docMonofont">)</span></span> </span></p></dt>
<dd><p class="docList">Resorts the array in random order. The key values are lost when the array is shuffled because the returned array is a numeric array. For example, <tt>shuffle($shapes);</tt> could place the value <tt>"Rectangle"</tt> in <tt>$shapes[0]</tt> using the array from <a class="docLink" href="#learnphpmysql-CHP-6-EX-2">Example 6-2</a>.</P></dd>
</dl>
<p class="docText">We've covered most everything you need to get going with PHP; it's now time to start introducing databases and MySQL in particular, then tackle how MySQL and PHP work synergistically.</P>


</TD></TR></table>
<br>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr><td><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-6.html><img src="images/prev.gif" width="60" height="17" border="0" align="absmiddle" alt="Previous Page"></a>
<td align="right"><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-6-SECT-2.html><img src="images/next.gif" width="60" height="17" border="0" align="absmiddle" alt="Next Page"></a>
</div></td></tr></table>
<script type="text/javascript"><!--
google_ad_client = "pub-0203281046321155";
google_alternate_ad_url = "http://www.bookhtml.com/adbrite.htm";
google_ad_width = 728;
google_ad_height = 90;
google_ad_format = "728x90_as";
google_ad_type = "text_image";
google_ad_channel ="4867465545";
google_color_border = "FFFFFF";
google_color_link = "0000FF";
google_color_bg = "FFFFFF";
google_color_text = "000000";
google_color_url = "0000FF";
//--></script>
<script type="text/javascript"
  src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</html>
